package org.openems;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.openems.meta.ParameterModelMeta;
import org.openems.model.ParameterModel;
import org.slim3.datastore.Datastore;

import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;

@Path("/parameter")
public class ParameterResource {
    public void takeSnapshot() {
        
    }
    
    @GET
    @Produces(MediaType.APPLICATION_XML)
    public ParameterEntity get(@QueryParam("key") String key) {
        ParameterModelMeta e = ParameterModelMeta.get();
        List<ParameterModel> ret = Datastore.query(e).filter(e.entityKey.equal(key)).filter(e.latest.equal(true)).asList();
        if (ret.size() == 1) {
            ParameterModel model = ret.get(0);
            return new ParameterEntity(model.getEntityKey(), model.getBlob().getBytes());
        }
        return new ParameterEntity();
    }
    
    @POST
    @Consumes(MediaType.APPLICATION_XML)
    @Produces(MediaType.TEXT_PLAIN)
    public String post(ParameterEntities parameterEntities) {
        String email = null;
        User user = UserServiceFactory.getUserService().getCurrentUser();
        if (user != null) {
            email = user.getEmail();
        }
        else {
            email = "annonymous";
        }
        
        List<ParameterModel> models = new ArrayList<ParameterModel>();
        for (ParameterEntity entity : parameterEntities.entities) {
            ParameterModelMeta e = ParameterModelMeta.get();
            List<ParameterModel> storedModels = Datastore.query(e).filter(e.entityKey.equal(entity.key)).asList();
            ParameterModel model = null;
            if (storedModels.size() == 0) {
                model = new ParameterModel();
            }
            else {
                model = storedModels.get(0);
            }
            model.setUserEmail(email);
            model.setEntityKey(entity.key);
            model.setBlob(new Blob(entity.body)); 
            model.setLatest(true);
            model.setProductName(parameterEntities.productName);
            model.setSerialNumber(parameterEntities.serialNumber);  
            models.add(model);
        }

        Datastore.put(models);
        
        return "OK";
    }
    
    @DELETE
    @Produces(MediaType.TEXT_PLAIN)
    public String delete() {
        ParameterModelMeta e = ParameterModelMeta.get();
        Datastore.delete(Datastore.query(e).asKeyList());
        return "OK";
    }
}
